package com.uam.web.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.uam.common.annotation.Log;
import com.uam.common.config.UAMConfig;
import com.uam.db.model.entity.DataLayer;
import com.uam.db.model.entity.DataRecord;
import com.uam.service.IDataLayerService;
import com.uam.service.IDataRecordService;
import com.uam.service.impl.PointServiceImpl;
import com.uam.utils.HttpUtils;
import com.uam.utils.StringUtils;
import com.uam.web.common.model.BusinessType;
import com.uam.web.common.model.PageData;
import com.uam.web.common.model.Result;
import com.uam.web.common.model.SysLayerConfig;
import com.uam.web.common.res.SysLayerRes;
import com.uam.web.common.utils.ResourceUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * 图层Controller
 *
 * @author uam
 * @date 2023-11-22
 */
@Controller
@RequestMapping("/data/layer")
@Api(tags = "图层")
@Slf4j
public class LayerController extends BaseController {

    @Autowired
    private IDataLayerService dataLayerService;
    @Autowired
    private IDataRecordService dataRecordService;
    @Autowired
    private UAMConfig uamConfig;

    @Autowired
    private PointServiceImpl pointService;

    /**
     * 系统图层树查询
     */
    @Log(title = "查看系统图层树", businessType = BusinessType.QUERY_LOG, isSaveResponseData = false)
    @ApiOperation(value = "查看系统图层树")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "用户登录token", paramType = "header"),
    })
    @PostMapping("/sys/tree/query")
    @ResponseBody
    public Result<SysLayerRes> sysTreeQuery() {
        SysLayerRes res = new SysLayerRes();
        log.info("查询系统图层树: {}", uamConfig.getSyslayerpath());
        SysLayerConfig sysLayerConfig = getSysLayerConfig(uamConfig.getSyslayerpath());
        res.setSysLayerList(Lists.newArrayList(sysLayerConfig.getSysLayerList()));
        for (SysLayerConfig.SysLayer sysLayer : res.getSysLayerList()) {
            if (sysLayer.getId().equals(sysLayerConfig.getDefaultSysLayerId())) {
                String content = ResourceUtils.getFileContent(sysLayer.getPath());
                sysLayer.setContent(JSON.parse(content));
                break;
            }
        }
        return Result.ok(res);
    }

    /**
     * 系统图层详情查询
     */
    @Log(title = "系统图层详情", businessType = BusinessType.SELECT, isSaveResponseData = false)
    @ApiOperation(value = "系统图层详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "用户登录token", paramType = "header"),
            @ApiImplicitParam(name = "id", value = "系统图层ID"),
    })
    @PostMapping("/sys/detail/query")
    @ResponseBody
    public Result<Object> sysDetailQuery(@RequestParam Integer id) {
        if (id == null) {
            return Result.paramError("");
        }

        //起降点统一数据格式
        //常规起降点
        if(id==8){
            return Result.ok(pointService.getPoint2GeoJson(1));
        }
        //备用起降点
        if(id==9){
            return Result.ok(pointService.getPoint2GeoJson(0));
        }

        SysLayerConfig sysLayerConfig = getSysLayerConfig(uamConfig.getSyslayerpath());
        SysLayerConfig.SysLayer sysLayer = sysLayerConfig.getSysLayerById(id);
        if (sysLayer != null) {
            String content = ResourceUtils.getFileContent(sysLayer.getPath());
            return Result.ok(JSON.parse((content)));
        }
        return Result.ok();
    }

    /**
     * 系统图层更新
     */
    @Log(title = "系统图层更新", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "系统图层更新")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "用户登录token", paramType = "header"),
            @ApiImplicitParam(name = "id", value = "系统图层ID"),
            @ApiImplicitParam(name = "content", value = "系统图层properties属性修改内容JSON"),
    })
    @PostMapping("/sys/update")
    @ResponseBody
    public Result sysUpdate(@RequestParam Integer id, @RequestParam String content) {
        log.info("修改数据Id:{},content:{}",id,content);
        if (id == null || StringUtils.isEmpty(content)) {
            return Result.paramError("");
        }
        SysLayerConfig sysLayerConfig = getSysLayerConfig(uamConfig.getSyslayerpath());
        SysLayerConfig.SysLayer sysLayer = sysLayerConfig.getSysLayerById(id);
        if (sysLayer != null) {
            boolean result = ResourceUtils.updateFileContent(sysLayer.getPath(), content);
            if (result) {
                try {
                    //调用更加实时计算接口
                    if (id == 14) {
                        JSONObject contentJs = JSONObject.parseObject(content);
                        JSONObject  extData = contentJs.getJSONObject("extData");
                        extData.put("id", contentJs.getString("id"));
                        //按照String类型传
                        extData.put("status",extData.getString("status"));
                        log.info("更新信息:id{} ：{}", id, JSONObject.toJSONString(extData));
                        String dataPostData= HttpUtils.post(uamConfig.getRouteUrl() + "/uam/route/base_station/update", new JSONObject(), JSONObject.toJSONString(extData));
                        log.info("返回信息：{}",dataPostData);
                        if(dataPostData!=null){
                            JSONObject dataPostDataJs = JSONObject.parseObject(dataPostData);
                            if(dataPostDataJs.getInteger("code")==0){
                                List dataInfo=dataPostDataJs.getJSONArray("data");
                                return Result.ok(dataInfo);
                            }
                        }

                    }
                }catch (Exception e){
                    log.error("更新错误:{} , content:{}",id,content,e);
                }
                return Result.ok();
            }
        }
        return Result.fail();
    }

    /**
     * 查询图层列表
     */
    @Log(title = "查询图层列表", businessType = BusinessType.QUERY_LOG)
    @ApiOperation(value = "查询图层列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "用户登录token", paramType = "header"),
            @ApiImplicitParam(name = "pageNum", value = "当前页"),
            @ApiImplicitParam(name = "pageSize", value = "分页条数")
    })
    @PostMapping("/list")
    @ResponseBody
    public Result<PageData<DataLayer>> list(@RequestParam(required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(required = false, defaultValue = "20") Integer pageSize) {
        DataLayer dataLayer = new DataLayer();
        dataLayer.setCreateName(getLoginName());
        Page<DataLayer> page = new Page(pageNum, pageSize);
        IPage<DataLayer> pageResult = dataLayerService.selectDataLayerList(page, dataLayer);
        return okPageData(pageResult);
    }

    /**
     * 图层添加
     */
    @Log(title = "图层添加", businessType = BusinessType.INSERT)
    @ApiOperation(value = "图层添加")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "用户登录token", paramType = "header"),
            @ApiImplicitParam(name = "dataRecordId", value = "选择数据ID"),
            @ApiImplicitParam(name = "layerName", value = "图层名称"),
    })
    @PostMapping("/add")
    @ResponseBody
    public Result add(@RequestParam Long dataRecordId, @RequestParam String layerName) {
        DataRecord dataRecord = dataRecordService.selectDataRecordById(dataRecordId);
        if (dataRecord == null) {
            return Result.fail("选择数据有误");
        }
        DataLayer dataLayer = new DataLayer();
        dataLayer.setDataId(dataRecordId);
        dataLayer.setLayerName(layerName);
        dataLayer.setDataType(dataRecord.getDataType());
        dataLayer.setDisplay(1);
        dataLayer.setCreateName(getLoginName());
        return toResult(dataLayerService.insertDataLayer(dataLayer));
    }

    /**
     * 图层重命名
     */
    @Log(title = "图层重命名", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "图层重命名")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "用户登录token", paramType = "header"),
            @ApiImplicitParam(name = "id", value = "图层数据ID"),
            @ApiImplicitParam(name = "layerName", value = "图层名称"),
    })
    @PostMapping("/edit")
    @ResponseBody
    public Result editSave(@RequestParam Long id, @RequestParam String layerName) {
        if (id == null || StringUtils.isEmpty(layerName)) {
            return Result.paramError("");
        }
        DataLayer dataLayer = new DataLayer();
        dataLayer.setId(id);
        dataLayer.setLayerName(layerName);
        return toResult(dataLayerService.updateDataLayer(dataLayer));
    }

    /**
     * 图层删除
     */
    @Log(title = "图层删除", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "图层删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "用户登录token", paramType = "header"),
            @ApiImplicitParam(name = "id", value = "图层数据ID"),
    })
    @PostMapping("/delete")
    @ResponseBody
    public Result delete(@RequestParam Long id) {
        if (id == null) {
            return Result.paramError("");
        }
        DataLayer dataLayer = new DataLayer();
        dataLayer.setId(id);
        dataLayer.setDisplay(0);
        return toResult(dataLayerService.updateDataLayer(dataLayer));
    }

    /**
     * 图层详情
     */
    @Log(title = "图层详情", businessType = BusinessType.SELECT, isSaveResponseData = false)
    @ApiOperation(value = "图层详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "用户登录token", paramType = "header"),
            @ApiImplicitParam(name = "id", value = "图层数据ID"),
    })
    @PostMapping("/detail")
    @ResponseBody
    public Result<DataRecord> detail(@RequestParam Long id) {
        if (id == null) {
            return Result.paramError("");
        }
        DataLayer dataLayer = dataLayerService.selectDataLayerById(id);
        if (dataLayer == null) {
            return Result.fail("图层数据有误");
        }
        DataRecord dataRecord = dataRecordService.selectDataRecordById(dataLayer.getDataId());
        if (dataRecord != null) {
            String fileContent = ResourceUtils.getFileContent(dataRecord.getDataUrl());
            dataRecord.setContent(JSON.parse(fileContent));
        }
        return Result.ok(dataRecord);
    }

    public static void main(String[] args) {
        String a = "[{\"offset\":[0,0],\"name\":\"航空公司\",\"position\":[112.78615818355513,28.45082199520523],\"type\":1},{\"offset\":[0,0],\"name\":\"航空公司\",\"position\":[112.7587650632455,28.32598894300658],\"type\":1},{\"offset\":[0,0],\"name\":\"航空公司\",\"position\":[112.90808597377458,28.395279802593322],\"type\":1},{\"offset\":[0,3],\"name\":\"航空公司\",\"position\":[112.87858271185178,28.301501594973388],\"type\":1},{\"offset\":[0,0],\"name\":\"航空公司\",\"position\":[112.75953181345153,28.214308278858013],\"type\":1}]";
        String b = "{\"features\":[{\"geometry\":{\"coordinates\":[112.9791803541,28.19199904],\"type\":\"Point\"},\"type\":\"Feature\",\"properties\":{\"maxangle\":10,\"maxfreq\":4900,\"range\":100000,\"type\":1,\"maxrange\":100000,\"antetype\":1,\"frequency\":\"4900\",\"name\":\"5G-ATG\",\"minfreq\":4840,\"angle\":10,\"id\":1,\"sector\":3,\"status\":1}},{\"geometry\":{\"coordinates\":[112.9902299041,28.1853054913],\"type\":\"Point\"},\"type\":\"Feature\",\"properties\":{\"maxangle\":0,\"maxfreq\":1070,\"range\":450000,\"type\":3,\"maxrange\":450000,\"antetype\":2,\"frequency\":\"1110\",\"name\":\"ADS-AAAAA\",\"minfreq\":1110,\"angle\":0,\"id\":2,\"sector\":1,\"status\":1}},{\"geometry\":{\"coordinates\":[113.00260963,28.1950731005],\"type\":\"Point\"},\"type\":\"Feature\",\"properties\":{\"maxangle\":10,\"maxfreq\":1561.098,\"range\":0,\"type\":2,\"maxrange\":0,\"antetype\":2,\"frequency\":\"1561.098\",\"name\":\"北斗卫星BBB\",\"minfreq\":1561.098,\"angle\":10,\"id\":3,\"sector\":1,\"status\":1}}],\"name\":\"point\",\"type\":\"FeatureCollection\"}";
        Object oa = JSON.parse(a);
        Object ob = JSON.parse(b);
        System.out.println(JSON.toJSONString(oa, SerializerFeature.DisableCircularReferenceDetect));
        System.out.println(JSON.toJSONString(ob, SerializerFeature.DisableCircularReferenceDetect));

        String sysLayerPath = "/Users/cwb/tempdata/system-layer-defualt.json";
        String path = "/Users/cwb/tempdata/point.json";
//        String path = "/www/uam/uam-web/static-file/point.json";

        String[] names = new String[]{"", "垂直起降点", "城市动态空域", "城市电磁环境", "航空公司", "空管部门", "临时障碍物",
                "长沙专题数据", "乘坐意愿热力图", "经济水平热力图", "商业区分布热力图", "平均收入热力图"};
        JSONObject root = new JSONObject();
        JSONArray jsonArray = new JSONArray(10);
        for (int i = 1; i <= 6; i++) {
            JSONObject child = new JSONObject();
            child.put("id", i);
            child.put("type", i);
            child.put("name", names[i]);
            child.put("path", path);
            jsonArray.add(child);
        }
        JSONObject child7 = new JSONObject();
        child7.put("id", 7);
        child7.put("type", 7);
        child7.put("name", names[7]);
        child7.put("path", path);
        jsonArray.add(child7);

        JSONArray childList = new JSONArray();
        for (int i = 8; i <= 11; i++) {
            JSONObject child = new JSONObject();
            child.put("id", i);
            child.put("type", i);
            child.put("name", names[i]);
            child.put("path", path);
            childList.add(child);
        }
        child7.put("childList", childList);
        root.put("defaultSysLayerId", 2);
        root.put("sysLayerList", jsonArray);
        System.out.println(JSONObject.toJSONString(root));

        SysLayerConfig sysLayerConfig = new BaseController().getSysLayerConfig(sysLayerPath);
        System.out.println(JSONObject.toJSONString(sysLayerConfig));
    }
}
